<?php
/**
 * Created by PhpStorm.
 * User: 李闯
 * Date: 2020/5/23
 * Time: 10:09
 */

namespace app\index\controller;


use app\service\TaskService;
use Redis\Redis;
use think\Db;

class BizStaff extends Common
{
    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 员工创建
     */
    function staffCreate()
    {
        /*
         * 注:满勤工资 满勤薪资 先不加  员工权限 不知道是不是 小程序的权限wx_authority 也先不加
         * 员工名称 :employee_name
         * 员工年龄:employee_age
         * 性别:employee_sex 员工性别(1-男 0-女 2未知)
         * 身份证号:employee_idcard
         * 手机号:employee_phone
         * 岗位id:jobs_id
         * 入职时间:employee_create
         * 转正时间:employee_positive
         * 试用期基础工资:basic_salary
         * 转正基础工资:positive_salary
         * 月休天数:employee_hugh
         * 员工状态:employee_status 状态( 1-试用期 2-正式员工 0-离职)
         * 主管设置:satrap  是否为主管 0 普通员工 1是\
         * 标识 mark == create 时  为创建 反之 是刚进入创建员工页面求 岗位的名称信息
         * */
        if (input("post.mark") == "create") {
            $info = input("post.");
            if (!empty($info)) {
                if (!checkMobile($info['employee_phone'])) {
                    return array('status' => false, 'msg' => '手机填写不正确');
                }
                #判断手机号是否重复
                $phone = Db::table('employee')->field('employee_phone')
                    ->where(array('employee_phone' => $info['employee_phone']))
                    ->where('employee_status != 0')
                    ->find();
                if (empty($phone)) {
                    # 验证身份证号
                    $idcard = IdentityCard::isValid($info['employee_idcard']);
                    if (!$idcard) {
                        return array('status' => false, 'msg' => '身份证号填写不正确');
                    }
                   $_info =  array(
                        'employee_name' => $info['employee_name'],
                        'employee_age' => $info['employee_age'],
                        'employee_sex' => $info['employee_sex'],
                        'employee_idcard' => $info['employee_idcard'],
                        'employee_phone' => $info['employee_phone'],
                        'employee_code' => $info['employee_phone'],
                        'jobs_info' => $info['jobs_info'],
                        'employee_create' => $info['employee_create'],
                        'employee_hugh' => $info['employee_hugh'],
                        'employee_status' => $info['employee_status'],
                        'wx_authority' => implode(',', $info['wx_authority']),
                        'biz_id' => $this->bizId
                    );
                    # 查询岗位id
                    $jobId = Db::table('jobs')->field('id')->where(array('jobs_title'=>$info['jobs_info']))->value('id');
                    if(!empty($jobId)){
                        $_info['jobs_id'] = $jobId;
                    }
                    #执行添加操作 员工信息表
                    $employee_id = Db::table('employee')->insertGetId($_info);

                    if ($employee_id) {
                        #员工关系表 employee_mapping
                        Db::table('employee_mapping')->insert(array(
                            'employee_positive' => $info['employee_positive'],
                            'employee_id' => $employee_id,
                            'basic_salary' => $info['basic_salary'],
                            'positive_salary' => $info['positive_salary'],
                            'trial_full' => $info['trial_full_salary'],//试用期满勤工资
                            'formal_full' => $info['worker_full_salary']//转正满勤工资
                        ));
                        $this->_Redis->hDel('employeeList', strval($this->bizId));
                        # 完成录入员工任务
                        TaskService::finishDayTask($this->bizId,2);
                        return array('status' => true, 'msg' => '创建成功');
                    } else {
                        return array('status' => false, 'msg' => '创建失败');
                    }
                } else {
                    return array('status' => false, 'msg' => '手机号重复,已有员工信息!');
                }
            } else {
                return array('status' => false, 'msg' => '获取创建数据为空');
            }
            #添加员工
        } else {
            #求岗位名称
            $info = Db::table('employee')->field('distinct jobs_info')->where("employee_status != 0 and del_status = 1")->select();
            if (!empty($info)) {
                return array('status' => true, 'data' => $info);
            } else {
                return array('status' => false);
            }
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 员工工资表
     */
    function staffPriceList()
    {
        getsNowMonthSalary();
        # 搜索日期
        $time = input('post.search');
        $mark = 2;
        # 查询门店信息
        $bizInfo = getsBizInfoArray($this->bizId, 1);
        if (empty($time) or $time == date('Y-m', strtotime('-1 month'))) {
            # 默认上个月的
            $mark = 1;
            $time = date('Y-m', strtotime('-1 month'));
            if ($bizInfo['biz_type'] == 1) {
                # 查询评论情况(所有员工中是否超过3个人有差评)
                $_evaluation = Db::query("select count(es.id) num,employee_id from evaluation_score es right join employee e on e.id = es.employee_id 
where e.scores_ranking = 1 and  date_format(create_time,'%Y-%m') = '" . $time . "' and evalua_level < 3 group by employee_id order by num desc ");

                if (!empty($_evaluation)) {
                    if ($_evaluation[0]['num'] >= 3 and $_evaluation[1]['num'] >= 3 and $_evaluation[2]['num'] >= 3)
                        $_bonusStatus = false;
                    else
                        $_bonusStatus = true;
                } else {
                    $_bonusStatus = true;
                }
                # 没有超过3个人
                if ($_bonusStatus == true) {
                    $_scoreInfo = array();
                    # 查询排行前三的人,(包括差评次数)
                    $_ranking = Db::query("select employee_id eid, sum(score) score,(select count(esc.id) from evaluation_score esc  
where esc.employee_id = eid and evalua_level < 3 and  date_format(create_time,'%Y-%m') = '" . $time . "') bad from evaluation_score es 
right join employee e on e.id = es.employee_id where e.scores_ranking = 1 
and date_format(create_time,'%Y-%m') = '" . $time . "' and e.biz_id=" . $this->bizId . " group by eid order by bad asc, score desc  ");
                    //没有差评评分排行人
                    $_bonusArr = array_filter($_ranking, function ($v) {
                        if (intval($v['bad']) == 0)
                            return true;
                    });
                    if (!empty($_bonusArr)) {
                        if (!empty($_bonusArr[0]['eid'])) {
                            $_scoreInfo[$_bonusArr[0]['eid']] = $_bonusArr[0];
                            $_scoreInfo[$_bonusArr[0]['eid']]['bonus'] = 500;
                        }
                        if (!empty($_bonusArr[1]['eid'])) {
                            $_scoreInfo[$_bonusArr[1]['eid']] = $_bonusArr[1];
                            $_scoreInfo[$_bonusArr[1]['eid']]['bonus'] = 300;
                        }
                        if (!empty($_bonusArr[2]['eid'])) {
                            $_scoreInfo[$_bonusArr[2]['eid']] = $_bonusArr[2];
                            $_scoreInfo[$_bonusArr[2]['eid']]['bonus'] = 100;
                        }
                    }

                }
            }
        }
        # 查询工资列表
        $salary = Db::table('salary s')
            ->field('s.id,employee_name,jobs_info,`employee_id`,`basic_salary`,`full_salary`,`deduct_salary`,`commission_salary`,`salary_time`,scores_ranking,
            `saleroom_price`,`comments_bonus`,`pract_basic`,`pract_full`,`attend`,`hugh_num`,`pract_att_days`')
            ->join('employee e', 'e.id=s.employee_id', 'right')
            ->where(array('biz_id' => $this->bizId))
            ->where("date_format(salary_time,'%Y-%m') = '$time'")
            ->select();
        foreach ($salary as $k => $v) {
            if (!empty($v['commission_salary'])) {
                $salary[$k]['count'] = $v['pract_basic'] + $v['pract_full'] + getsPriceFormat($v['commission_salary']) + sprintf("%.2f", $v['saleroom_price']) + getsPriceFormat($v['comments_bonus']) - $v['deduct_salary'];
                $salary[$k]['commission_salary'] = getsPriceFormat($v['commission_salary']);
                $salary[$k]['bonus'] = getsPriceFormat($v['saleroom_price']) + getsPriceFormat($v['comments_bonus']);
                # 剩余休息天数
                $residue_hugh = intval($v['hugh_num']) - intval($v['attend']);
                if ($residue_hugh < 0) $residue_hugh = 0;
                $salary[$k]['residue_hugh'] = $residue_hugh;
            } else {
                # 奖金
                $bonus = 0;
                # 扣款
                $_bad = 0;
                # 获取员工提成
                $deduct = getsEmployeeDeduct($v['employee_id'], $time);
                if (empty($deduct)) {
                    $deduct = 0;
                }
                $salary[$k]['commission_salary'] = getsPriceFormat($deduct);
                # 查询该员工扣款
                $_deductions = getsEmployeeDeduct($v['employee_id'], $time, false);
                $salary[$k]['deduct_salary'] = $_deductions;
                # 获取员工工资情况
                $basicfull = getsEmployeebasic($v['employee_id'], $v['basic_salary'], $v['full_salary'], date('Y-m-01', strtotime($time)));
                $salary[$k]['pract_basic'] = $basicfull['pract_basic'];
                $salary[$k]['pract_full'] = $basicfull['pract_full'];
                $salary[$k]['attend'] = $basicfull['attend'];
                $salary[$k]['hugh_num'] = $basicfull['hugh_num'];
                $salary[$k]['pract_att_days'] = $basicfull['pract_att_days'];
                # 剩余休息天数
                $residue_hugh = intval($basicfull['hugh_num']) - intval($basicfull['attend']);
                if ($residue_hugh < 0) $residue_hugh = 0;
                $salary[$k]['residue_hugh'] = $residue_hugh;
                if($v['basic_salary'] != $basicfull['pract_basic']){
                    $salary[$k]['basic_salary'] = $basicfull['pract_basic'];
                    $salary[$k]['full_salary'] = $basicfull['pract_full'];
                    Db::table("salary")->where(array("id" => $v['id']))->update(array(
                        'commission_salary' => getsPriceFormat($deduct),
                        'pract_basic' => $basicfull['pract_basic'],
                        'basic_salary' => $basicfull['pract_basic'],
                        'pract_full' => $basicfull['pract_full'],
                        'full_salary' => $basicfull['pract_full']
                    ));
                }
                # 如果是默认上月搜索
                if (date("d", time()) >= config('ecarcoo.salaryDate') and $mark == 1) {
                    if (empty($this->_Redis->get('salary' . $v['id']))) {
                        $this->_Redis->set('salary' . $v['id'], 1);
                        # 当前时间为结算日期 将员工提成写入员工工资表
                        Db::table("salary")->where(array("id" => $v['id']))->update(array(
                            'commission_salary' => getsPriceFormat($deduct),
                            'pract_basic' => $basicfull['pract_basic'],
                            'deduct_salary' => $_deductions,
                            'pract_full' => $basicfull['pract_full'],
                            'attend' => $basicfull['attend'],
                            'hugh_num' => $basicfull['hugh_num'],
                            "pract_att_days" => $basicfull['pract_att_days']
                        ));
                        if ($bizInfo['biz_type'] == 1) {
                            # 销售额打成奖励
                            $_bonus = getsEmployeeBonus($v['employee_id'], date("Y-m", strtotime("-1 month")));
                            if ($_bonus['status'] == 2) {
                                $bonus += $_bonus['employee_bonus'];
                                Db::table("salary")->where(array("id" => $v['id']))->update(array("saleroom_price" => $_bonus['employee_bonus']));
                            } else {
                                Db::table("salary")->where(array("id" => $v['id']))->update(array("saleroom_price" => 0));
                            }
                            # 根据评论计算奖金
                            # 所有员工中有超过3人有差评,奖金取消
                            # 排名前三并且没有差评,第一名:奖金500  第二名:奖金300  第三名:奖金100
                            if (!empty($_scoreInfo)) {
                                if (array_key_exists($v['employee_id'], $_scoreInfo)) {
                                    if ($_scoreInfo[$v['employee_id']]['bad'] <= 0) {
                                        $bonus += $_scoreInfo[$v['employee_id']]['bonus'];
                                        Db::table("salary")->where(array("id" => $v['id']))->update(array("comments_bonus" => $_scoreInfo[$v['employee_id']]['bonus']));
                                    } else {
                                        Db::table("salary")->where(array("id" => $v['id']))->update(array("comments_bonus" => 0));
                                    }
                                } else {
                                    Db::table("salary")->where(array("id" => $v['id']))->update(array("comments_bonus" => 0));
                                }
                            }
                            # 查询该员工差评的订单数,一次差评扣款50
                            $_badReview = Db::query("select count(distinct order_id) num from evaluation_score 
where employee_id = " . $v['employee_id'] . " and date_format(create_time,'%Y-%m') = '" . $time . "' and evalua_level < 3");
                            if (!empty($_badReview) and !empty($_badReview[0]['num'])) {
                                $_bad = getsPriceFormat((50 * $_badReview[0]['num']));
                                Db::table('salary')->where(array('id' => $v['id']))->setInc('deduct_salary', $_bad);
                            } else {
                                $_bad = 0;
                            }
                        }
                    }
                }
                $salary[$k]['bonus'] = $bonus;
                # 实际发放
                $salary[$k]['count'] = $basicfull['salary'] + getsPriceFormat($deduct) + $_deductions + $bonus - $_bad;
                # 实际工资
                $salary[$k]['real'] = $basicfull['salary'];
                # 合计工资
                $salary[$k]['total'] = $basicfull['salary'] + getsPriceFormat($deduct);
            }
            # 计算评论总分
            $_totalInfo = Db::query("select sum(score) total,(select count(id) from evaluation_score 
where employee_id = " . $v['employee_id'] . " and date_format(create_time,'%Y-%m') = '" . $time . "' and evalua_level=5 and biz_id=" . $this->bizId . ") good,
(select count(id) from evaluation_score where employee_id = " . $v['employee_id'] . " and date_format(create_time,'%Y-%m') = '" . $time . "' and (evalua_level=4 or evalua_level=3) 
and biz_id=" . $this->bizId . ") middle,
 (select count(id) from evaluation_score where employee_id = " . $v['employee_id'] . " and date_format(create_time,'%Y-%m') = '" . $time . "' and evalua_level < 3 
 and biz_id=" . $this->bizId . ") bad 
 from evaluation_score where employee_id = " . $v['employee_id'] . " and date_format(create_time,'%Y-%m') = '" . $time . "' and biz_id=" . $this->bizId);
            $salary[$k]['totalScore'] = $_totalInfo[0]['total'];
            $salary[$k]['good'] = $_totalInfo[0]['good'];
            $salary[$k]['middle'] = $_totalInfo[0]['middle'];
            $salary[$k]['bad'] = $_totalInfo[0]['bad'];
        }
        $_arrayYes = array();
        $_arrayNo = array();
        foreach ($salary as $k => $v) {
            if ($v['scores_ranking'] == 1) {
                $_arrayYes[] = $salary[$k];
            } else {
                $_arrayNo[] = $salary[$k];
            }
        }
        # 按照评论得分进行从高到低排序
        array_multisort(array_column($_arrayYes, 'totalScore'), SORT_DESC, $_arrayYes);
        array_multisort(array_column($_arrayNo, 'totalScore'), SORT_DESC, $_arrayNo);
        $_salaryArr = array_merge($_arrayYes, $_arrayNo);
        $this->_Redis->hSetJson('salary' . $this->bizId, $time, $_salaryArr);
        return array('status' => true, 'data' => $_salaryArr);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 员工历史薪资
     */
    function historicalSalary()
    {
        # 查询该员工的历史薪资
        if (empty($this->employeeId)) {
            return array('status' => false, 'msg' => '员工ID为空');
        }
        $_where = "";
        # 接收查询年份
        $year = Input('post.year');
        if (!empty($year)) {
            $_where = "date_format(salary_time,'%Y') = '" . $year . "'";
            if ($year == date('Y')) {
                $_where .= " and date_format(salary_time,'%Y-%m') <= '" . date('Y-m', strtotime('-2 months')) . "'";
            }
        }
        # 查询员工开工资的年份
        $_year = Db::table('salary')
            ->field('date_format(salary_time,"%Y") year')
            ->where(array('employee_id' => $this->employeeId))
            ->group('year')
            ->order('year')
            ->select();
        if (!empty($_year)) {
            $_year = array_column($_year, 'year');
        }
        # 查询员工历史薪资
        $info = Db::table('salary')
            ->field('date_format(salary_time,"%m") month,basic_salary basics,commission_salary full,saleroom_price royalty,full_salary bonus,deduct_salary fine')
            ->where(array('employee_id' => $this->employeeId))
            ->where($_where)
            ->order('month')
            ->select();
        if (!empty($info)) {
            foreach ($info as $k => $v) {
                $info[$k]['whole'] = getsPriceFormat((floatval($v['basics']) + floatval($v['full']) + floatval($v['royalty']) + floatval($v['bonus']) - floatval($v['fine'])));
            }
        }
        return array('status' => true, 'info' => $info, 'year' => $_year);
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content  修改手机号
     */
    function writePhone()
    {
        # 接收手机号
        $phone = input("post.phone");
        # 接收填写的验证码
        $code = input('code');
        if (!empty($phone) and !empty($code)) {
            if ($this->loginType == 1) {
                #先看看是不有重复的手机号
                $biz_phone = Db::table('biz')->field('id,biz_phone')->where(array('biz_phone' => $phone))->find();
            } else {
                # 员工登录
                $biz_phone = Db::table('employee')->field('id,employee_phone')->where(array('employee_phone' => $phone))->find();
            }
            if (!empty($biz_phone)) {
                return array('status' => false, 'msg' => '手机号重复,请换个手机号修改');
            } else {
                #把验证码存一下redis
                $redis = new Redis();
                # 从redis中获取改手机号是否存在验证码
//                $codeNum = $redis->hGet('SmsCode', $phone);
                $codeNum = '123456';
                if ($code != $codeNum) {
                    return array('status' => false, 'msg' => '验证码不正确');
                }
                if ($this->loginType == 1) {
                    $result = Db::table('biz')->where(array('id' => $this->bizId))->update(array('biz_phone' => $phone));
                } else {
                    # 员工登录
                    $result = Db::table('employee')->where(array('id' => $this->employeeId))->update(array('employee_phone' => $phone));
                }
                if ($result) {
                    return array('status' => true, 'msg' => '修改成功');
                } else {
                    return array('status' => false, 'msg' => '修改失败');
                }
            }
        }
    }
}
